<template>
  <v-row class="fileList-container" no-gutters>
    <v-col class="flex-grow-0 prepend">
      <slot name="prepend">
        <v-file-input
          @change="uploadFile"
          multiple
          class="file-input"
          ref="fileInput"
          type="file"
        />
        <v-icon color="#79839B" @click="clickFileInput" class="icon pointer"
          >mdi-folder</v-icon
        >
      </slot>
    </v-col>
    <v-col class="file-list">
      <viewer :images="syncedImages" class="clearfix">
        <template #default="scope">
          <v-row class="images" no-gutters>
            <v-col
              :cols="2"
              class="image-wrap"
              v-for="img in scope.images"
              :key="img.id"
            >
              <img :src="img.src" :alt="img.name" class="image" />
            </v-col>
          </v-row>
        </template>
      </viewer>
    </v-col>
  </v-row>
</template>

<script lang="ts">
import { Vue, Component, PropSync } from "vue-property-decorator";
import { readerFile } from "@/common/constants/Utils";
import VFileInput from "vuetify/src/components/VFileInput";
type VFileInputInstance = InstanceType<typeof VFileInput>;

interface IImage {
  id: string;
  src: string;
  name: string;
}

@Component({
  components: {},
})
export default class FileList extends Vue {
  @PropSync("images", {
    type: Array,
    default: () => [],
  })
  syncedImages!: Array<IImage>;

  clickFileInput() {
    (this.$refs.fileInput as VFileInputInstance).$refs.input.click();
  }

  async uploadFile(files: HTMLInputElement["files"]) {
    if (!files) return;
    for (let i = 0; i < files.length; i++) {
      const file = files[i];
      const reader: FileReader = await readerFile(file);
      if (!reader.error) {
        // 文件转base64成功
        const fileObj = {
          id: `${new Date().getTime()}${file.name}`,
          src: reader.result as string,
          name: file.name,
        };
        this.syncedImages.push(fileObj);
      } else {
        // 文件转base64失败
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import "./FileList.scss";
</style>
